﻿[<AutoOpen>]
module FODATAC.Extensions

open System.Runtime.CompilerServices
open System.Linq
open FODATAC.Interfaces.Internal
open System.Linq.Expressions

type Expression with
    
    member this.GetCollectionName() = 
        match this with
        | :? MethodCallExpression as me -> this.GetCollectionName(me)
        | :? ConstantExpression as ce -> this.GetCollectionName(ce)
        | _ -> failwith "invalid collection name type"
    
    member this.GetCollectionName(methodCallExpression : MethodCallExpression) = 
        match methodCallExpression.Arguments.[0] with
        | :? ConstantExpression as ce -> this.GetCollectionName ce
        | :? MethodCallExpression as me -> this.GetCollectionName me
        | _ -> failwith "Unsupported expression"
    
    member this.GetCollectionName(constantExpression : ConstantExpression) : string = (constantExpression.Value :?> ILinqQuery).CollectionName

type System.String with
    member this.AddParameter param = 
        let formatted = 
            if this.Contains("?") then "{0}&{1}"
            else "{0}?{1}"
        System.String.Format(formatted, this, param)
(*
internal static string AddParameter(this string url, string param)
        {
            return string.Format(url.Contains("?") ? "{0}&{1}" 
                : "{0}?{1}", url, param);
        }

(**)
    
  public static class ExpressionExtensions
    {
        public static string GetCollectionName(this Expression expression)
        {
            return GetCollectionName(expression as MethodCallExpression);
        }


        public static string GetCollectionName(MethodCallExpression methodCallExpression)
        {
            var constantExpression = methodCallExpression.Arguments[0] as ConstantExpression;


            if (constantExpression != null)
            {
                return GetCollectionName(constantExpression);
            } 


            return GetCollectionName(methodCallExpression.Arguments[0] as MethodCallExpression);
        }


        public static string GetCollectionName(ConstantExpression constantExpression)
        {
            return (constantExpression.Value as IOQuery).CollectionName;
        }
        public static int YearCompare(this DateTime date)
        {
            return date.Year;
        }
        public static int MonthCompare(this DateTime date)
        {
            return date.Month;
        }
        public static int DayCompare(this DateTime date)
        {
            return date.Day;
        }
        public static int MinuteCompare(this DateTime date)
        {
            return date.Minute;
        }
        public static int Length(this string input)
        {
            return input.Length;
        }
    }
}
*)
